package demo1;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2024-07-24
 * Time: 12:40
 */
public class HashBuck2<K,V> {
    static class Node<K,V>{  //没有体会到为什么写Node<K,V>模型
        public K key;
        public V val;
        public Node<K,V> next;
        //内部类构造方法
        public Node(K key , V val){
            this.key = key;
            this.val = val;
        }
    }
    public Node<K,V>[] array;
    public int usedSize;
    public static final float DEFAULT_LOAD_FACTOR = 0.75f;
    public HashBuck2(){
        array = (Node<K, V>[]) new Node[10];//强转为kv模型的数组,警报不用管
    }
    public void put(K key,V val){
        int hash = key.hashCode();//把key转换为可比较的数值，最好用重写的hashCode
        int index = hash % array.length;
        Node<K,V> cur = array[index];
        while (cur != null){
            if (cur.key.equals(key)  ){
                //if (cur.key == key ){   //key不是整型啊，得用equals()
                cur.val = val;
                return;
            }
            cur = cur.next;

        }
        //头插法.先实例化一个节点
        Node<K,V> node = new Node(key,val);
        node.next = array[index];
        array[index] = node;
        usedSize++;
    }
    public V getValue(K key){
        //第一步：确定下标
        int hash = key.hashCode();//Object类自带的方法，我们自己写的类，直接可以点出来
        int index = hash % array.length;
        Node<K,V> cur = array[index];
        //第二步：遍历链表
        while (cur != null){
            if (cur.key.equals(key) ){
                return cur.val;
            }
            cur = cur.next;
        }

        return null;
    }
    


}
